package bean.managed;

import entity.AddressEntity;
import bean.managed.util.JsfUtil;
import bean.managed.util.PaginationHelper;
import bean.session.AddressEntityFacade;

import entity.ContactEntity;
import java.io.Serializable;
import java.util.List;
import java.util.ResourceBundle;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.ActionEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import managedbean.AbstractBacking;
import type.AddressType;

@ManagedBean(name = "addressEntityController")
@SessionScoped
public class AddressEntityController extends AbstractBacking implements Serializable {

    private AddressEntity current;
    private DataModel items = null;
    @EJB
    private bean.session.AddressEntityFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private ContactEntity contact;
    private List<AddressEntity> allAddresses;
    @ManagedProperty(value = "#{contactEntityController}")
    private ContactEntityController contactEntityController;

    @PostConstruct
    public void initContact() {
        contact = contactEntityController.getCurrent();
        System.out.println("PostConstruct: " + contact);

        allAddresses = ejbFacade.getAddressesForContact(contact);
    }

    public AddressEntityController() {
    }

    public AddressEntity getSelected() {
        if (current == null) {
            current = new AddressEntity();
            selectedItemIndex = -1;
        }
        return current;
    }

    public AddressEntity getCurrent() {
        return current;
    }

    public void setCurrent(AddressEntity current) {
        this.current = current;
    }

    private AddressEntityFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}, contact));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (AddressEntity) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        recreateModel();
        current = new AddressEntity();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            current.created(getLoginPerson());
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AddressEntityCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (AddressEntity) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            current.modified(getLoginPerson());
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AddressEntityUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public void updateOrEditWithoutRedirect() {
        System.out.println("in updateOrCreate without redirect: " + current);
        try {
            if (getSelected().getId() == null) {
                current.setContact(contact);
                allAddresses.add(current);
                contact.setAddresses(allAddresses);
                current.created(getLoginPerson());
                getFacade().create(current);
                System.out.println("New address created: " + current);
            } else {
                current.modified(getLoginPerson());
                getFacade().edit(current);
                System.out.println("New address edited: " + current);
            }
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AddressEntityUpdated"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    public String destroy() {
        current = (AddressEntity) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    public void setupCurrentBasedOnContactController() {
        contact = contactEntityController.getCurrent();
//        System.out.println("setup addresses: " + contact);

        allAddresses = ejbFacade.getAddressesForContact(contact);
//        current = new AddressEntity();
    }

    private void performDestroy() {
        try {
            current.modified(getLoginPerson());
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AddressEntityDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        current=null;
        items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }
    
    public SelectItem[] getShippingAddressesAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.getAddressByTypeForContact(getContact(), AddressType.ShippingAddress), true);
    }
    
    public SelectItem[] getShippingAddressesAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.getAddressByTypeForContact(getContact(), AddressType.ShippingAddress), false);
    }
    
    public SelectItem[] getBillingAddressesAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.getAddressByTypeForContact(getContact(), AddressType.BillingAddress), true);
    }

    @FacesConverter(forClass = AddressEntity.class, value="addressConverter")
    public static class AddressEntityControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0 || value.trim().length() == 0) {
                return null;
            }
            AddressEntityController controller = (AddressEntityController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "addressEntityController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            try{
                key = Long.valueOf(value);
            }catch(NumberFormatException e){
                return -1L;
            }
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null ) {
                return null;
            }
            if (object instanceof AddressEntity) {
                AddressEntity o = (AddressEntity) object;
                return getStringKey(o.getId());
            } else if(object instanceof String){
                System.out.println("converted string: " + (String)object);
                return null;
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + AddressEntityController.class.getName());
            }
        }
    }

    public ContactEntity getContact() {
        setupCurrentBasedOnContactController();
        return contact;
    }

    public void setContact(ContactEntity contact) {
        this.contact = contact;
    }

    public ContactEntityController getContactEntityController() {
        return contactEntityController;
    }

    public void setContactEntityController(ContactEntityController contactEntityController) {
        this.contactEntityController = contactEntityController;
    }

    public List<AddressEntity> getAllAddresses() {
        setupCurrentBasedOnContactController();
        return allAddresses;
    }

    public void setAllAddresses(List<AddressEntity> allAddresses) {
        this.allAddresses = allAddresses;
    }

    public void prepareNewAddress() {
        System.out.println("In prepare new address: ");
        current = null;
    }

    public AddressType[] getAddressTypes() {
        return AddressType.values();
    }
}
